extends TextureRect

var current_mix: Array[String] = []
var name_map: Dictionary = {} #记录ID对应中文名
var color_map: Dictionary = {} #用来记录 ID 对应的颜色

@export var all_recipes: Array[RecipeData]
@onready var info_label = %InfoPanel.get_child(0) # 确保你使用了唯一名称，或者用 find_child
@onready var timer = $Timer
@onready var main = find_parent("MainBar")
@onready var shaker_area2: TextureRect = $ShakerArea2
@onready var shaker_area3: TextureRect = $ShakerArea3


#预加载音效文件
var sfx_open = preload("res://sound/bar/shaker_open.wav")
var sfx_close = preload("res://sound/bar/shaker_clouse.wav")
var sfx_shake = preload("res://sound/bar/shaker_shake.wav")
var sfx_add = preload("res://sound/bar/basewine_add.wav") # 加酒
var sfx_empty = preload("res://sound/bar/basewine_add.wav") # 倒空 (暂时复用加酒，或者你有倒水声)
var sfx_pull = preload("res://sound/bar/mixwine_pull.wav")

func _ready():
	#连接信号
	$MixButton.pressed.connect(mix_drink)
	$EmptyButton.pressed.connect(_on_empty_pressed)
	timer.timeout.connect(_on_timer_show_content)
	mouse_entered.connect(_start_timer)
	mouse_exited.connect(_reset_timer)
	
	#监听全局状态
	if Global.has_signal("game_state_changed"):
		Global.game_state_changed.connect(_on_game_state_changed)
	
	update_buttons_state() 


func _on_game_state_changed(can_interact: bool):
	#如果正在对话 (不可交互)
	if not can_interact:
		#直接禁用
		$MixButton.disabled = true
		$EmptyButton.disabled = true
	else:
		#恢复交互时，重新根据杯子里的原料数量决定亮不亮
		update_buttons_state()

func update_buttons_state():
	var count = current_mix.size()
	
	#逻辑判断：有1个能倒，有2个能混合
	var can_empty = (count >= 1) 
	var can_mix = (count >= 2)
	
	#只修改开关状态
	$EmptyButton.disabled = not can_empty
	$MixButton.disabled = not can_mix
	
	#强制把颜色重置为白色
	$EmptyButton.modulate = Color.WHITE
	$MixButton.modulate = Color.WHITE

#倒掉酒(清空)
func _on_empty_pressed():
	
	current_mix.clear()
	name_map.clear()
	color_map.clear()
	main.play_sfx(sfx_pull)
	update_buttons_state()
	
	if info_label.get_parent().visible:
		_on_timer_show_content()
	
	#print("杯子已清空")
	main.show_floating_text("杯子已倒空！", Color.GRAY)
	#这里可以播放倒水的声音

#悬停0.5s显示内容
func _start_timer():
	timer.start()

func _reset_timer():
	if shaker_area3.visible == true:
		main.play_sfx(sfx_close)
	
	shaker_area2.visible = true
	shaker_area3.visible = false
	timer.stop()
	info_label.get_parent().hide()

func _on_timer_show_content():
	#如果杯子是空的
	if current_mix.is_empty():
		if shaker_area2.visible == true:
			main.play_sfx(sfx_open)
		shaker_area2.visible = false
		shaker_area3.visible = true
		info_label.text = "[b]调酒杯[/b]\n空空如也..."
	else:
		#如果有东西，统计数量
		var content_text = get_content_text()
		info_label.text = "[b]当前混合:[/b]\n" + content_text
	
	info_label.get_parent().show()

func get_content_text() -> String:
	var counts = {}
	
	#计数
	for id in current_mix:
		if id in counts:
			counts[id] += 1
		else:
			counts[id] = 1
			
	#拼接字符串(修改这里)
	var result_str = ""
	for id in counts:
		#获取中文名
		var display_name = name_map.get(id, id) 
		var count = counts[id]
		var amount_oz = count * 0.25
		var color = color_map.get(id, Color.WHITE)
		var hex = color.to_html(false)
		
		result_str += "- [color=#%s]%s[/color]: %.2f oz\n" % [hex, display_name, amount_oz]
	
	return result_str

#保持原有的拖拽逻辑
func _can_drop_data(at_position, data):
	return data is Dictionary and data.get("type") == "ingredient"

func _drop_data(at_position, data):
	var ing_id = data["id"] #这里获取的是ID字符串
	var ing_name = data["name"] #获取中文名
	var ing_color = data["color"]
	current_mix.append(ing_id)
	main.play_sfx(sfx_add)
	name_map[ing_id] = ing_name
	color_map[ing_id] = ing_color
	
	update_buttons_state()
	
	main.show_floating_text("加入了：" + ing_name, Color.GREEN_YELLOW)
	
	#如果鼠标正悬停在杯子上加料，立即刷新文字
	if not timer.is_stopped() or info_label.get_parent().visible:
		timer.stop() #重置计时器防止冲突
		_on_timer_show_content() #直接刷新显示

func mix_drink():
	if current_mix.is_empty():
		get_tree().current_scene.show_floating_text("杯子是空的...", Color.GRAY, global_position)
		return
	
	main.play_sfx(sfx_shake)
	await play_shake_anim()
	
	var result_recipe = null
	
	#统计当前原料
	var current_counts = {}
	for id in current_mix:
		if id in current_counts:
			current_counts[id] += 1
		else:
			current_counts[id] = 1
			
	print("\n========== 调酒开始 ==========")
	print("我的杯子里有: ", current_counts)
	
	for recipe in all_recipes:
		print("----------------------------")
		print("正在比对配方: ", recipe.name)
		print("配方要求: ", recipe.ingredients)
		
		if check_recipe(current_counts, recipe.ingredients):
			print(">>> 匹配成功！<<<")
			result_recipe = recipe
			break
		else:
			print(">>> 不匹配")
	print("============================\n")

	# 检查结果
	if result_recipe:
		if create_drink_instance(result_recipe):
			main.show_floating_text("调制成功！", Color.GOLD, global_position)
			
			current_mix.clear()
			name_map.clear()
			update_buttons_state()
	else:
		main.show_floating_text("这杯酒估计不会好喝...", Color.BROWN)
		print("配方错误，生成了一杯淤泥")

	#清空逻辑
	current_mix.clear()
	name_map.clear()
	update_buttons_state()

#比对函数
func check_recipe(current: Dictionary, required: Dictionary) -> bool:
	if current.size() != required.size(): return false
	for k in required:
		if current.get(k, 0) != required[k]: return false
	return true

func create_drink_instance(recipe: RecipeData) -> bool:
	
	var serve_zone = get_tree().current_scene.find_child("DrinkServeZone")

	if serve_zone.get_child_count() >= 3:
		main.show_floating_text("桌子放不下了！", Color.RED)
		return false 
	
	#加载成品酒场景
	var drink_scene = load("res://scene/drink_item.tscn").instantiate()
	drink_scene.setup(recipe)
	#添加到ServeZone节点下
	serve_zone.add_child(drink_scene)
	
	return true

func play_shake_anim():
	var target = $ShakerArea2
	
	#记录原始位置，防止摇完回不去
	var original_pos = target.position
	var original_rot = target.rotation
	
	#创建动画
	var tween = create_tween()
	
	#摇晃逻辑：上下快速抖动 10 次
	for i in range(40):
		#随机生成一点点偏移量
		var offset_y = randf_range(-40.0, 20.0) 
		var offset_rot = randf_range(-3.0, 3.0) #角度偏移
		
		#0.04秒内移动到随机位置
		tween.tween_property(target, "position:y", original_pos.y + offset_y, 0.05)
		tween.parallel().tween_property(target, "rotation_degrees", offset_rot, 0.05)
	
	#最后归位
	tween.tween_property(target, "position", original_pos, 0.05)
	tween.parallel().tween_property(target, "rotation", original_rot, 0.05)
	
	#等待动画播放完毕
	await tween.finished
	
